package com.xbaoziplus.simple_spring.beans.factory.support;

import com.xbaoziplus.simple_spring.beans.BeansException;
import com.xbaoziplus.simple_spring.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @author xbaozi
 * @version 1.0
 * @classname CglibSubclassingInstantiationStrategy
 * @date 2023-04-20  20:18
 * @description Cglib实例化策略
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        // 设置空的回调
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if (null == ctor) {
            // 使用无参构造器实例化对象
            return enhancer.create();
        }
        // 使用与argumentTypes参数匹配的超类的构造函数和给定的参数实例化对象
        return enhancer.create(ctor.getParameterTypes(), args);
    }
}
